﻿Imports Training.Common
Imports System.IO
Imports System.Text
Imports System.Security

Partial Public Class BulkUserUpload
    Inherits System.Web.UI.Page
    Dim ftprcs As String ' file to process
    Dim uCreated As Boolean ' user created

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    ''' <summary>
    ''' Create Users Button Click event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click
        If Page.IsValid Then
            UploadFile()
            processData(GetDataFromExcel())
        Else
            lblResults.Text = "Page validation failed, no action was performed."
        End If
    End Sub

    ''' <summary>
    '''  upload the file
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub UploadFile()
        Dim fn As String ' file name
        Dim fileUploaded As Boolean

        ' initial value of fileUploaded & usercreated
        fileUploaded = False

        fn = fuMain.PostedFile.FileName

        ' define path to upload folder
        Dim p As String
        p = Server.MapPath("csvs")

        Try
            ' upload the actual file
            fuMain.PostedFile.SaveAs(p & "\" & System.IO.Path.GetFileName(fn.ToString()))
            ' set fileUploaded
            fileUploaded = True
            ftprcs = System.IO.Path.GetFileName(fn.ToString())
        Catch ex As Exception
            ' also log error here
            fileUploaded = False
            Throw ex
        End Try

        ' check if upload completed
        If fileUploaded Then
            ' it worked, process file
            lblResults.Text = "file uploaded"
        Else
            ' upload failed, notify user
            lblResults.Text = "upload failure"
        End If

    End Sub

    ''' <summary>
    ''' load csv into a datable
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetDataFromExcel() As DataTable
        Dim con As System.Data.Odbc.OdbcConnection
        Dim dt As New DataTable()
        Dim da As System.Data.Odbc.OdbcDataAdapter
        Dim conStr As String
        Dim impf As String
        Dim fn As String

        impf = Server.MapPath("csvs")
        fn = ftprcs

        conStr = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + impf + ";"
        con = New Odbc.OdbcConnection(conStr)

        da = New System.Data.Odbc.OdbcDataAdapter("select * from [" + fn + "]", con)
        da.Fill(dt)

        Return dt
    End Function

    ''' <summary>
    ''' Process user data from csv and import users
    ''' </summary>
    ''' <param name="dt"></param>
    ''' <remarks></remarks>
    Private Sub processData(ByVal dt As DataTable)
        Dim uName As String ' username
        Dim uPass As String ' password
        Dim fName As String ' firstname
        Dim lName As String ' lastname
        Dim cmp As String ' company
        Dim zip As String ' zip
        Dim phn As String ' phone
        Dim eml As String ' email
        Dim blnU As Boolean ' username check result
        Dim blnE As Boolean ' email check result
        Dim eMsg As String ' email message

        For Each row As DataRow In dt.Rows

            ' inital value of login and email check
            blnU = False
            blnE = False

            ' populate variables
            uName = row(0) & "." & row(1)
            fName = row(0)
            lName = row(1)
            cmp = row(2)
            zip = row(3)
            phn = row(4)
            eml = row(5)

            ' check username and email for duplicates
            If CheckLoginName(uName) = 0 Then
                blnU = True
            Else
                ' append random number to username to create account
                uName = uName & RandomNumber(1, 999)
                If CheckLoginName(uName) = 0 Then
                    blnU = True
                End If
            End If

            ' *** unique emails are being depreciated, this will be removed ***
            'If CheckMemberEmail(eml) = 0 Then
            '    blnE = True
            'End If

            ' either create membership account or flag as duplicate
            If blnU Then
                ' generate a uniqe password
                uPass = Membership.GeneratePassword(6, 0)

                ' add users to membership
                Membership.CreateUser(uName, uPass, eml)
                Roles.AddUserToRole(uName, "user")

                ' add group user information:::
                ' lookup userid for user to associate login with user table
                Dim user As MembershipUser = Membership.GetUser(uName)
                Dim uid As String = user.ProviderUserKey.ToString()

                ' insert the user data
                If AddGroupUser(uid, fName, lName, CType(ddlGroups.SelectedValue, Integer), cmp, "", "", ddlState.SelectedValue, zip, phn, eml, "", 1) <> 0 Then
                    Response.Write("ERROR creating group account for " & uName)
                    Exit Sub
                End If

                eMsg = "Your Training account is now active.<br />" & _
                    "Your login name is: " & uName & "<br />" & _
                    "Your login password is: " & uPass & "<br />" & _
                    "Contact you@yourdomain.com if you experience problems logging in."

                'send the user their login and password
                SendEmail(eml, "Your Training Account", eMsg)
            Else
                'send the admin an email with the duplicate info
                eMsg = "DUPLICATE USER in bulk user creation. Account for: " & _
                    uName & " could not be created."

                SendEmail("group@yourdomain.com", "Bulk User Creation Error", eMsg)
            End If
        Next row

        lblProcessing.Text = "User processing complete."
    End Sub

    ''' <summary>
    ''' random number generator
    ''' </summary>
    ''' <param name="MaxNumber"></param>
    ''' <param name="MinNumber"></param>
    ''' <returns></returns>
    ''' <remarks>could be used to generate unique logins if necessary</remarks>
    Public Function RandomNumber(ByVal MaxNumber As Integer, ByVal MinNumber As Integer) As Integer

        'initialize random number generator
        Dim r As New Random(System.DateTime.Now.Millisecond)

        'if passed incorrect arguments, swap them
        'can also throw exception or return 0

        If MinNumber > MaxNumber Then
            Dim t As Integer = MinNumber
            MinNumber = MaxNumber
            MaxNumber = t
        End If

        Return r.Next(MinNumber, MaxNumber)

    End Function
End Class